import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex);//vue的插件机制

//Vuex.Store 构造器选项
const store = new Vuex.Store({
	state:{//存放状态
		"carList": uni.getStorageSync('carList') || []
	},
	"getters": {
		// 根据carList进行数量求和
		"allCount": (state) => {
			return state.carList.reduce((prev,next) => {
					return prev + next.count
			},0)
		},
		// 根据carList进行总价求和
		"totalPrice": (state) => {
			return state.carList.filter(item => item.checked).reduce((prev,next) => {
				return prev + next.count * next.price
			}, 0)
		},
		// 根据carList进行全选按钮状态的计算
		"totalCheck": (state) => {
			return state.carList.every(item => item.checked)
		}
	},
	"mutations": {
		// 加购
		// 1.判断是否购物车有当前商品
		// 2.有当前商品,进行count+1
		// 3.没有当前商品,进行unshfit追加
		addCar(state, payload) {
			const itemInfo = state.carList.find(item => item.id === payload.id)
			if(itemInfo) {
				itemInfo.count += 1;
			} else {
				state.carList.unshift({...payload, count: 1})
			}
			uni.setStorageSync('carList', state.carList)
		},
		// 加数量
		// 遍历carList,对匹配到的商品count进行+1
		addCount(state, payload) {
			const {id} = payload;
			state.carList = state.carList.map(item => {
				if(item.id === id) {
					return {
						...item,
						count: item.count + 1
					}
				}
				return item
			})
			uni.setStorageSync('carList', state.carList)
		},
		// 减数量
		// 遍历carList,对匹配到的商品count进行-1
		subCount(state, payload) {
			const {id} = payload;
			state.carList = state.carList.map(item => {
				if(item.id === id) {
					return {
						...item,
						count: item.count - 1
					}
				}
				return item
			})
			uni.setStorageSync('carList', state.carList)
		},
		// 单个勾选框勾选/不勾选
		// 遍历carList,对匹配到的商品checked字段进行修改
		checkItem(state, payload) {
			const {id, checked} = payload;
			state.carList = state.carList.map(item => {
				if(item.id === id) {
					return {
						...item,
						checked: checked
					}
				}
				return item
			})
			uni.setStorageSync('carList', state.carList)
		},
		// 全选勾选框勾选/不勾选
		// 遍历carList,对所有商品checked字段进行修改
		checkAll(state, payload) {
			const {checked} = payload;
			state.carList = state.carList.map(item => ({...item,checked}))
			uni.setStorageSync('carList', state.carList)
		}
	}
})
export default store